﻿module Sustainalytics.Portfolio {
    import Common = Sustainalytics.Common;

    export class PortfolioCompanyService implements IPortfolioCompanyService {

        private $q: ng.IQService;
        private $http: ng.IHttpService;
        private notificationFactory: Common.INotificationFactory;
        private staticObjects: Common.IStaticObjects;
        private urlBase: string;

        // Ctor.
        public constructor($q: ng.IQService, $http: ng.IHttpService, notificationFactory: Common.INotificationFactory, staticObjects: Common.IStaticObjects) {
            this.$q = $q;
            this.$http = $http;
            this.notificationFactory = notificationFactory;
            this.urlBase = staticObjects.portfolioBaseUrl;
        }

        // show error message for a given error code
        private showError(err) {
            var ctx = this;
            if (err && err['code'])
                ctx.notificationFactory.error('', ctx.staticObjects.getErrorMesageByStatusCode(err, err['code']));
        }

        private showInformation(inf) {
            var ctx = this;
            if (inf && inf['code'])
                ctx.notificationFactory.success("The company is in the selected portfolio!");
        }
        
        // get paged list of portfolio
        public getPortfolioCompanies(filter: PortfolioCompanyFilterDto, skip: number, take: number, orderBy: string[], orderByAsc: boolean, accountId: string, userId: string) {
            var ctx = this;
            var def = this.$q.defer();

            var options = new Common.ListOptions();
            options.skip = skip;
            options.take = take;
            options.orderBy = orderBy;
            options.orderAscending = orderByAsc;
            options.includeAllFields = true;
            options.getCount = false;

            var params = $.param({
                accountId: accountId,
                userId: userId,
                listOptions: options
            });

            var url = this.urlBase + "/api/v1/portfolios/" + filter.portfolioId + "/portfolioCompanies?" + params;
            var promise = this.$http.get(url);

            promise.success(
                function (data) {
                    def.resolve(data);
                }).error(
                function (err) {
                    ctx.showError(err);
                    def.reject();
                })

            return def.promise;
        }

        //get count of portfolios
        public getPortfolioCompaniesCount(filter: PortfolioCompanyFilterDto, accountId: string, userId: string) {
            var ctx = this;
            var def = this.$q.defer();

            var options = new Common.ListOptions();
            options.skip = null;
            options.take = null;
            options.orderBy = null;
            options.orderAscending = null;
            options.includeAllFields = false;
            options.getCount = true;

            var params = $.param({
                accountId: accountId,
                userId: userId,
                listOptions: options
            });

            var url = this.urlBase + "/api/v1/portfolios/" + filter.portfolioId + "/portfolioCompanies?" + params;
            var promise = this.$http.get(url);

            promise.success(
                function (data) {
                    def.resolve(data);
                }).error(
                function (err) {
                    ctx.showError(err);
                    def.reject();
                })

            return def.promise;
        }

        //deletePortfolio
        public deletePortfolioCompany(id: string, portfolioId: string) {
            var ctx = this;
            var def = this.$q.defer();

            var url: string = this.urlBase + '/api/v1/portfolios/'+ portfolioId+ '/portfolioCompanies/' + id;

            var promise: ng.IHttpPromise<{}> = this.$http['delete'](url);

            promise.success(function (data) {
                //ctx.showMessage("Portfolio deleted successfully!");
                def.resolve(data);
            })
                .error(function (err) {
                    ctx.showError(err);
                    def.reject();
                })
            return def.promise;
        }

        //post PortfolioCompany
        public insertPortfolioCompany(id: string, portfolioId: string) {
            var ctx = this;
            var def = this.$q.defer();

            var url: string = this.urlBase + '/api/v1/portfolios/' + portfolioId + '/portfolioCompanies/' + id;

            var promise: ng.IHttpPromise<{}> = this.$http.post(url, null);

            promise.success(function (data) {
                if (data && data['errorCode'] && data['errorCode'] == 5103) {
                    ctx.notificationFactory.success("The company already exists in the selected portfolio!");
                }
                if (data == '') {
                    ctx.notificationFactory.success("Succesfully added");
                }
                def.resolve(data);
            })
                .error(function (err) {
                    ctx.showError(err);
                    def.reject();
                })
            return def.promise;
        }
    }

    // register service with Portfolio Angular module
    angular.module('Sustainalytics.Portfolio').factory('PortfolioCompanyService', function ($q: ng.IQService, $http: ng.IHttpService, notificationFactory: Common.INotificationFactory, staticObjects: Common.IStaticObjects) {
        var srv = new PortfolioCompanyService($q, $http, notificationFactory, staticObjects);
        return srv;
    });
}
